<template>
  <div class="full_edit">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :default-config="toolbarConfig"
      mode="default"
    >
    </Toolbar>
    <Editor
      class="editor"
      :default-config="editorConfig"
      v-model="valueHtml"
      mode="default"
      @onCreated="handleCreated"
      @onChange="handleChange"
      @onDestroyed="handleDestroyed"
      @customPaste="customPaste"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css';
import { shallowRef, ref, watch } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { BASE_URL, base } from '@/service/config';
type InsertFnType = (url: string, alt?: string, href?: string) => void;

const valueHtml = ref('');
const editorRef = shallowRef();
const toolbarConfig = {};

const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: BASE_URL + '/file/upload',
      fieldName: 'files',
      async customInsert(res: any, insertFn: InsertFnType) {
        // TS 语法
        // customInsert(res, insertFn) {                  // JS 语法
        // res 即服务端的返回结果

        // 从 res 中找到 url alt href ，然后插入图片
        console.log(res);

        insertFn(base + res.data.url, '出错了', base + res.data.url);
      }
    }
  }
};

// 编辑器回调函数
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleChange = (editor) => {
  // console.log('change:', valueHtml.value);
  // emit('update:valueHtml', editor.getHtml());
};
const handleDestroyed = (editor) => {
  console.log('destroyed', editor);
};

const customPaste = (editor, event, callback) => {
  // console.log('ClipboardEvent 粘贴事件对象', event);

  // 自定义插入内容
  // editor.insertText('xxx');

  // 返回值（注意，vue 事件的返回值，不能用 return）
  // callback(false); // 返回 false ，阻止默认粘贴行为
  callback(true); // 返回 true ，继续默认的粘贴行为
};

defineExpose({ valueHtml, editorRef });
</script>

<style scoped lang="less">
.full_edit {
  border: 1px solid #ccc;
  height: 100%;
  display: flex;
  flex-direction: column;

  .editor {
    flex: 1;
    overflow-y: auto;
  }
}
</style>
